package com.wmh.baseservice.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.user.pojo.UsIncomeExpend;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.UsTopUpWithdrawal;
import com.wmh.baseservice.user.mapper.UsTopUpWithdrawalMapper;
import com.wmh.baseservice.user.service.UsIncomeExpendService;
import com.wmh.baseservice.user.service.UsInfoService;
import com.wmh.baseservice.user.service.UsTopUpWithdrawalService;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author wmh generator
 * @since 2022-08-27
 */
@Service
public class UsTopUpWithdrawalServiceImpl extends CommonServiceImpl<UsTopUpWithdrawalMapper, UsTopUpWithdrawal> implements UsTopUpWithdrawalService {

    @Resource
    private UsInfoService usInfoService;
    @Resource
    private UsIncomeExpendService usIncomeExpendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void topUp(String orderNum) {
        //修改充值单状态
        UsTopUpWithdrawal usTopUpWithdrawal = getOneForUpdate(new QueryWrapper<UsTopUpWithdrawal>().eq(UsTopUpWithdrawal.ORDER_NUM, orderNum));
        usTopUpWithdrawal.setStatus(1);
        if (!updateById(usTopUpWithdrawal)) {
            throw new ServiceException();
        }
        //修改用户余额
        UsInfo usInfo = usInfoService.getByIdForUpdate(usTopUpWithdrawal.getUsId());
        usInfo.setBalance(usInfo.getBalance().add(usTopUpWithdrawal.getMoney()));
        if (!usInfoService.updateById(usInfo)) {
            throw new ServiceException();
        }
        //添加用户流水
        UsIncomeExpend usIncomeExpend = new UsIncomeExpend().setUsId(usTopUpWithdrawal.getUsId()).setRemark("微信充值余额").setType(1).setOrderNum(usTopUpWithdrawal.getOrderNum())
                .setStatus(1);
        if (!usIncomeExpendService.save(usIncomeExpend)) {
            throw new ServiceException();
        }
    }
}
